#include <iostream>
#include <string>
#include <cstring>
#include <cstdlib>
#include <unistd.h>
#include <sys/wait.h>

int main()
{
    int fd[2] = {0};
    int n = pipe(fd);
    if (n != 0)
    {
        std::cerr << "pipe error" << std::endl;
    }

    pid_t id = fork();
    if(id < 0)
    {
        std::cerr << "fork" <<std::endl;
        return 2;
    }
    else if (id == 0)
    {
        // 子进程
        close(fd[0]);
        int cnt = 0;
        int sum = 0;
        while (true)
        {
            // std::string message = "hello pipe,hello";
            std::string message = "h";
            // message += std::to_string(getpid());
            // message += ",";
            // message += std::to_string(cnt);
            // cnt++;
            //write(fd[1], message.c_str(), message.size());
            sum += write(fd[1], message.c_str(), message.size());
            std::cout << sum << std::endl;
            //sleep(1);
            // break;
        }
        exit(0);
    }
    else
    {
        // 父进程
        close(fd[1]);
        char buffer[1024];
        while (true)
        {
            int r = read(fd[0], buffer, 1024);
            if (r > 0)
            {
                buffer[r] = 0;
                std::cout << "child->father: " << buffer << std::endl;
            }
            else if (r == 0)
            {
                std::cout << "n:" << n << std::endl;
                std::cout << "child quit ??? me too" << std::endl;
                break;
            }
            //close(fd[0]);
            //break;
            sleep(10000);
        }
        int status = 0;
        int rid = waitpid(id, &status, 0);
        if (rid > 0)
        {
            std::cout << "father wait child success: " << "exit code:" << ((status<<8)&0xFF)
            << ",exit sig:" << (status&0x7F) << std::endl;
        }
        else
        {
            std::cerr << "waitpid" << std::endl;
        }
    }
    return 0;
}